##########################################################
## 2025-05-01 harrydeep@wardyan.top
## 定时任务. 只要引用本模块，就会自动执行定时任务
##########################################################


from apscheduler.schedulers.background import BackgroundScheduler
from top.wardyan.core.vo.mqtt import MqttMsg
from top.wardyan.core.mqtt import mqttconfig
from top.wardyan.core.erp.erp import *
from top.wardyan.core.utils.common import *
from top.wardyan.core.wdb.core.db import *
import uuid
import shutil
import time
import json


SQL_IDS = "SELECT k.sTableName, k.sKeyField, SUM(CAST(CASE WHEN k.xEndValue >= k.xValue THEN k.xEndValue - k.xValue ELSE 0 END AS bigint)) AS xQty, COUNT(1) AS xCnt FROM dbo.st_keyvalue AS k GROUP BY k.sTableName, k.sKeyField"

## 心跳 写死固定1分钟一次

scheduler = BackgroundScheduler()




scheduler.add_job(mqttconfig.mqtt_heartbeat, 'interval', seconds=60)



def get_disk_usage(path="/"):
    total, used, free = shutil.disk_usage(path)
    
    # 转换为 GB
    total_gb = total // (2**30)
    used_gb = used // (2**30)
    free_gb = free // (2**30)

    return total_gb, used_gb, free_gb

## 每天上报一次服务器信息: 磁盘空间, ID使用情况, 执行情况
def send_system_info():
    ##msg = MqttMsg(str(uuid.uuid4()), "2025-05-01", "system/info", "disk: 10%, cpu: 10%, memory: 10%, process: 10%", "wardyan", "wardyan", 1)
    ## 查询磁盘空间大小及已使用
    total_gb, used_gb, free_gb = get_disk_usage()
    ids = query(SQL_IDS)
    data = {
        "disktotal": total_gb,
        "diskused": used_gb,
        "diskfree": free_gb,
        "erpversion": ERP_LASTUPDATE(),
        "ids" : ids
    }
    time.sleep(1)
    s = json.dumps(data, ensure_ascii=False)
    ## 计算s有多少KB
    #s = len(s) / 1024
    print("发送系统信息: {} KB".format(len(s) / 1024))
    ## 压缩消息内容

    msg = MqttMsg(topic=mqttconfig.TOPIC, message=s,business=0,)
    mqttconfig.send(mqttconfig.TOPIC, msg)




















scheduler.start()


if __name__ == "__main__":
    send_system_info()